#pragma once

//
//   Sets default system font for specified window.
//
void SetDefaultFont(HWND hWnd)
{
	NONCLIENTMETRICS ncm;
	static HFONT hDefaultFont;

	if (!hDefaultFont)
	{
		SecureZeroMemory(&ncm, sizeof(ncm));
		ncm.cbSize = sizeof(ncm);
		SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, NULL);
		hDefaultFont = CreateFontIndirect(&ncm.lfMenuFont);
	}

	SendMessage(hWnd, WM_SETFONT, (WPARAM)hDefaultFont, 0);
}

//
//   Opens hyperlink in a default browser window.
//
void OpenHyperlink(const SimpleString &hyperlink)
{
	SHELLEXECUTEINFO shexec;

	SecureZeroMemory(&shexec, sizeof(shexec));
	shexec.lpFile = hyperlink.ToCharArray();
	shexec.lpVerb = _T("open");
	shexec.nShow = SW_SHOWNORMAL;
	shexec.cbSize = sizeof(shexec);

	ShellExecuteEx(&shexec);
}

SimpleString &GetUserId()
{
	TCHAR szUserName[MAX_PATH];
	DWORD dwUserNameLen;
	static SimpleString *szUserId = nullptr;

	if (!szUserId)
	{
		SecureZeroMemory(szUserName, MAX_PATH * sizeof(TCHAR));
		GetUserNameEx(NameSamCompatible, szUserName, &dwUserNameLen);
		szUserId = new SimpleString(szUserName);
	}

	return (*szUserId);
}

SimpleString &FormatTaskXml()
{
	HRSRC	hXml;
	HGLOBAL	hData;
	DWORD	dwXmlSize;
	LPTSTR	szXmlFormat, szFullPath, szEnvPath, szExePath;
	
	hXml = FindResource(NULL, MAKEINTRESOURCE(IDR_TASK_XML), L"XML");
	if (!hXml)
	{
		throw;
	}

	hData = LoadResource(NULL, hXml);
	if (!hData)
	{
		throw;
	}

	dwXmlSize = SizeofResource(NULL, hXml);
	szXmlFormat = (LPTSTR)LockResource(hData);

	szFullPath = new TCHAR[MAX_PATH];
	GetModuleFileName(NULL, szFullPath, MAX_PATH);
	szEnvPath = new TCHAR[MAX_PATH];
	szExePath = PathUnExpandEnvStrings(szFullPath, szEnvPath, MAX_PATH) ? szEnvPath : szFullPath;

	const TCHAR *szUserId = GetUserId().ToCharArray();
	SimpleString *result = &SimpleString::Format(szXmlFormat, szUserId, szExePath);

	UnlockResource(hData);
	
	delete[] szFullPath;
	delete[] szEnvPath;
	
	return (*result);
}
